<template>
  <el-dialog
    title="地图"
    :visible.sync="mapDialog"
    width="90%"
    @open="open()"
    @close="mapDialogClose"
    center
  >
    <div v-loading="isLoading">
      <span class="coordinateText">{{ `当前经度: ${currentLng}，当前纬度: ${currentLat}` }}</span>
      <div id="mapBox" @click="handleMapClick"></div>
      <div class="dialog-footer">
        <cs-btn
          type="primary"
          @click.native="confirmBtnClick"
          btnText="确定"
          class="confirm_btn dialog_btn"
          :buttonStatus="buttonStatus"
        />
        <cs-btn @click.native="cancelBtnClick" btnText="取消" class="dialog_btn" />
      </div>
    </div>
  </el-dialog>
</template>

<script>
import csBtn from '@/components/cs-btn/cs-btn.vue'
// import { addressToCoordinate, coordinateToAddress } from '@/service/TMap/TMap'

export default {
  components: {
    csBtn
  },
  data() {
    return {
      mapDialog: false,
      key: 'LWFBZ-RH6W6-GIVSQ-M7VID-625VK-LXBGK',
      map: {},
      addresslng: 109.120464,
      addresslat: 21.481857,
      currentLat: '',
      currentLng: '',
      markerLayer: {},
      isLoading: false,
      buttonStatus: false
    }
  },
  created() {
    this.$bus.$on('showMap_site', (address) => {
      if (address) {
        this.addressToCoordinate(address)
      } else {
        this.getLocationByIP()
      }
      this.mapDialog = true
    })
    this.$bus.$on('showMap_enterprise', (address) => {
      if (address) {
        this.addressToCoordinate(address)
      } else {
        this.getLocationByIP()
      }
      this.mapDialog = true
    })
  },
  beforeDestroy() {
    console.log('TMap销毁了')
  },
  methods: {
    open() {
      this.loadScript()
    },
    // 初始化地图
    initMap(lat = this.addresslat, lng = this.addresslng) {
      // 定义地图中心点坐标
      const center = new TMap.LatLng(lat, lng)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      this.map = new TMap.Map(document.getElementById('mapBox'), {
        center: center, // 设置地图中心点坐标
        zoom: 17.2, // 设置地图缩放级别
        pitch: 43.5, // 设置俯仰角
        rotation: 45, // 设置地图旋转角度
        viewMode: '2D'
      })
      this.setMapPoint()
      // 设置地图坐标标记
      this.markerLayer.add([
        {
          id: '1',
          // styleId: 'myStyle',
          position: new TMap.LatLng(lat, lng),
          properties: {
            // 自定义属性
            title: 'marker3'
          }
        }
      ])
      this.currentLng = lng
      this.currentLat = lat
    },
    loadScript() {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${this.key}&callback=init`
      script.onload = script.onreadystatechange = () => {
        if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
          this.initMap()
          script.onload = script.onreadystatechange = null
        }
      }
      document.body.appendChild(script)
    },
    // 获取地图点击坐标
    getLocation(evt) {
      this.currentLat = evt.latLng.getLat().toFixed(6)
      this.currentLng = evt.latLng.getLng().toFixed(6)

      // 清空地图显示坐标标记
      this.markerLayer.setGeometries([])
      // 设置地图坐标标记
      this.markerLayer.add([
        {
          id: '1',
          // styleId: 'myStyle',
          position: new TMap.LatLng(this.currentLat, this.currentLng),
          properties: {
            // 自定义属性
            title: 'marker3'
          }
        }
      ])
    },
    // 处理地图点击事件
    handleMapClick() {
      this.map.on('click', this.getLocation)
    },
    async getLocationByIP() {
      this.isLoading = true
      const data = await this.$jsonp('https://apis.map.qq.com/ws/location/v1/ip', {
        key: 'LWFBZ-RH6W6-GIVSQ-M7VID-625VK-LXBGK',
        output: 'jsonp'
      })
      console.log(data)
      if (data.status === 0) {
        this.addresslat = data.result.location.lat
        this.addresslng = data.result.location.lng
        this.isLoading = false
      } else {
        this.$message.error('根据IP定位失败')
        this.isLoading = false
      }
    },
    // 地址转坐标
    async addressToCoordinate(address) {
      this.isLoading = true
      const data = await this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1', {
        address,
        key: this.key,
        output: 'jsonp'
      })
      console.log(data)
      if (data.status === 0) {
        this.addresslat = data.result.location.lat
        this.addresslng = data.result.location.lng
        this.isLoading = false

        // this.$nextTick(() => {
        //   this.map.setCenter(new TMap.LatLng(this.addresslat, this.addresslng))
        // })

        // this.$nextTick(() => {
        //   if (this.map) {
        //     this.map.destroy()
        //   }
        // })

        // this.initMap(this.addresslat, this.addresslng)
        // const center = new TMap.LatLng(this.addresslng, this.addresslat)
        // this.map.panTo(center, 500)
        // this.map.setCenter(new TMap.LatLng(this.addresslat, this.addresslng))
      } else {
        this.$message.error('地址转换经纬度失败')
        this.isLoading = false
      }
    },
    // 设置地图点位
    setMapPoint() {
      this.markerLayer = new TMap.MultiMarker({
        map: this.map, // 指定地图容器
        // 样式定义
        styles: {
          // 创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
          myStyle: new TMap.MarkerStyle({
            width: 25, // 点标记样式宽度（像素）
            height: 35, // 点标记样式高度（像素）
            // src: '../img/marker.png', // 图片路径
            // 焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
            anchor: { x: 16, y: 32 }
          })
        },
        // 点标记数据数组
        geometries: []
      })
    },
    async coordinateToAddress(lat, lng) {
      const data = await this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1', {
        location: lat + ',' + lng,
        key: this.key,
        output: 'jsonp'
      })
      if (data.status === 0) {
        this.address = data.result.address
      } else {
        this.$message.error('经纬度转换地址失败')
        this.buttonStatus = false
      }
    },
    async confirmBtnClick() {
      this.buttonStatus = true
      await this.coordinateToAddress(this.currentLat, this.currentLng)
      this.$bus.$emit('confirmCoordinate', this.currentLng, this.currentLat, this.address)
      this.mapDialog = false
    },
    cancelBtnClick() {
      this.mapDialog = false
    },
    mapDialogClose() {
      this.map.destroy()
      this.buttonStatus = false
    }
  }
}
</script>

<style scoped>
#mapBox {
  width: 100%;
  height: 600px;
  margin-bottom: 30px;
}

.coordinateText {
  position: absolute;
  top: 23px;
  left: 100px;
  font-weight: 700;
}
</style>
